/*
 * Copyright 2010 Christopher Z. Collier
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.xorf.caveman.gui;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.Map.Entry;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

import net.xorf.caveman.core.FileUtils;
import net.xorf.caveman.core.HbmResourceRunner;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.swixml.SwingEngine;


public class CavemanGuiMain {
    private static Logger log = LoggerFactory.getLogger(CavemanGuiMain.class);

    private HbmResourceRunner resourceRunner;
    private JFrame mainFrame;
    
    public JButton runButton;
    public EasyJTable configPropsList;
    public EasyJTable resourcesList;
    public JTextPane messagesPane;

    static {
        org.apache.log4j.PropertyConfigurator.configureAndWatch("log4j.properties");
    }
    
    public CavemanGuiMain() throws Exception {
        SwingEngine swixmlEngine = new SchemaBuilderSwixmlEngine(this);

        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        Container container = swixmlEngine.render("net/xorf/caveman/gui/cavemanMainWindow.xml");
        
        ((JFrame)container).setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        StreamRedirector.redirectSystemStreamsTo(messagesPane);

        container.setVisible(true);
    }

    public final Action runResources = new AbstractAction() {
        public final void actionPerformed(ActionEvent evt) {
            resourceRunner.run();
        }
    };

    public final Action loadConfig = new AbstractAction() {
        public final void actionPerformed(ActionEvent evt) {
            File configFile = new EasyFileChooser(mainFrame, "loadConfig")
                .addFilter(".cfg.xml", "Hibernate configuration files")
                .chooseSingleFile();
            
            if (configFile == null) return;
            String configFilePath = configFile.getPath();
            resourceRunner = new HbmResourceRunner(configFilePath);

            for (Entry<Object, Object> e : resourceRunner.getConfigProperties().entrySet()) {
                configPropsList.addRow(new Object[] { 
                        e.getKey().toString(),
                        e.getValue().toString() });
            }           
        }
    };
    
    public final Action addResources = new AbstractAction() {
        public final void actionPerformed(ActionEvent evt) {
            File[] resourceFiles = new EasyFileChooser(mainFrame, "addResources")
                .addFilter(".hbm.xml,.jar", "Hibernate mapping resources")
                .chooseMultiFiles();
            
            for (File resourceFile : resourceFiles) {
                resourceRunner.addResource(resourceFile.getPath());
                resourcesList.addRow(new Object[] { resourceFile.getName(),
                    FileUtils.getExtension(resourceFile), resourceFile.getPath() });
            }
            
            runButton.setEnabled(true);
        }
    };

    public final Action clearMessages = new AbstractAction() {
        public final void actionPerformed(ActionEvent evt) {
            Document doc = messagesPane.getDocument();
            try {
                doc.remove(0, doc.getEndPosition().getOffset() - 1);
            } catch (BadLocationException e) {
                throw new RuntimeException(e);
            }
        }
    };
    
    public static void main(String[] args) throws Exception {
        log.info(String.format("starting %s...", CavemanGuiMain.class.getName()));
        
        new CavemanGuiMain();
    }
}
